<template>
  <div class="wrapper">
    <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '15px' }" />
    <div>
      <FormPanel ref="from" :list="initForm" :cols="3" :formType="value.type" :labelWidth="120" :isSubmitBtn="false"
        :isCollapse="false" @formChange="changeHandle" />
    </div>

    <!-- 新增附件上传 begin -->
    <BreakSpace label="附件信息" :containerStyle="{ marginBottom: '15px' }" />
    <Spin :spinning="picLoading" tip="Loading...">
      <FilterTable ref="picTable" :columns="picColumns" :dataSource="picFiles" :params="picParams" height="auto"
        :datakey="'records'" :isSelectColumn="false" :isColumnFilter="false" :isPagination="false"
        :onRowSelectChange="selectChange" :onColumnsChange="picColumns => (this.picColumns = picColumns)">
      </FilterTable>
    </Spin>
    <!-- 查看凭证 -->
    <el-image-viewer :url-list="picList" v-show="imagesViewShow" :on-close="closeImagesViewer"></el-image-viewer>
    <!-- 新增附件上传 end -->

    <BreakSpace label="备件列表" :containerStyle="{ marginBottom: '15px' }" />
    <FilterTable height="300" ref="dealerRoleTable" :columns="partColumns" :dataSource="partList"
      :isSelectColumn="isSelectColumn" :datakey="'records'" :onSyncTableData="syncPjFun"
      :onColumnsChange="partColumns => (this.partColumns = partColumns)" columnsRef="notification_maintain_info_02">
    </FilterTable>
    <BreakSpace label="审核记录" :containerStyle="{ marginBottom: '15px' }" />
    <FilterTable ref="table" :columns="approveColumns" :dataSource="dataList1" :datakey="'records'"
      :isSelectColumn="false" columnsRef="notification_maintain_index_02"
      :onColumnsChange="columns => this.columns = columns">
    </FilterTable>
    <!-- <approveHistory v-model="approvalparams" /> -->

    <BaseDialog :visible.sync="approveDialogFlag" title="1审核原因" width="30%" destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <div style="height:300px">
        <FormPanel ref="from2" :list="initForm2" :cols="3" :formType="value.type" :labelWidth="120" :isSubmitBtn="false"
          :collapse="false" @formChange="changeHandle2" />
      </div>
      <!-- <div :style="{
        textAlign: 'center'
      }">
        <el-button :loading="loadingFlag" @click="saveDialog(saveState)" type="primary">保 存</el-button>
        <el-button @click="closeRefuseDialog()">返 回</el-button>
      </div> -->
    </BaseDialog>
    <div class="dialogBottmView" :style="{
      textAlign: 'center'
    }">
      <!-- <el-button :loading="loadingFlag" @click="saveDialog('30441002')" type="primary">审核通过</el-button>
      <el-button :loading="loadingFlag" @click="refuse('30441003')" type="primary">审核驳回</el-button> -->
      <el-button @click="closeDialog('closeDialog')">返 回</el-button>
    </div>
  </div>
</template>

<script>

import { getFileGroup } from '@/api/partsmanage/common/file';
import { getPartsGroup, postApprove, getApproveRecord, getClaimRefundInfo } from '@/api/partsmanage/claimRefundManage/audit';
// import approveHistory from '../../components/approveHistory';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import config from '@/assets/js/config';

// import { deletePartFileById } from '@/api/partsmanage/aduitOrder/aduitClaim';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import axios from '@/api/fetch';
import { async } from 'q';

export default {
  name: 'chaimapproveinfo',
  mixins: [dictionary],
  props: {
    value: {
      type: Object,
      required: true
    },
  },
  components: {
    // approveHistory,
    ElImageViewer
  },
  data() {
    this.saveData = null;
    this.saveData2 = null;
    return {
      type: this.value.type,
      claimid: this.value.data.id,
      initForm: this.initFormFun(),
      initForm2: this.initFormFun2(),
      partColumns: this.creatHeaderPartColumns(),
      approveColumns: this.creatHeaderApproveColumns(),
      partList: [],
      approveRecordList: [],
      isSelectColumn: false,
      approveDialogFlag: false,
      formData: {},
      orderid: '',
      loadingFlag: false,
      saveState: '',
      // spryduty :'',
      bjthlx: '',
      approvalparams: {},
      ACCEPT_AMOUNT: '',
      // aduitePrice: '',
      picLoading: false,
      picColumns: this.createPicTable(),
      picFiles: [],
      picParams: { xtdjid: '', xtfjlx: 'part_rtgoods' },
      uploadPrefix: config.uploadUrl,// 附件上传前缀
      form: { fileList: [] },
      picLimit: 5,
      picList: [],
      imagesViewShow: false,
      dataList1: [],
      auditSwitch: false,
      jhdInfodisabled: false,
    };
  },
  created() {
    this.init(this.value.data)
    // this.type = this.value.type
    // console.log(this.value)
  },
  methods: {
    async init(data) {

      console.log('data', data)
      this.applyNum = data.applyNum
      this.id = data.id

      // 明细基本信息
      const refundInfo = await getClaimRefundInfo({ 'id': this.id });
      // 初始化表格信息
      const detailRes = await getPartsGroup({'applyNum':this.applyNum});
      console.log('进来了没有', detailRes.data)
      if (detailRes.resultCode === 200 && Array.isArray(detailRes.data.records) && detailRes.data.records.length > 0) {
        console.log('进来了没有2', detailRes)
        this.partList = Object.assign({}, { 'total': detailRes.data.records.length }, {'records': detailRes.data.records});
      }
      console.log('partList', this.partList)

      // getPartsGroup({ 'applyNum': this.applyNum }).then(response => {
      //   this.partList = response.data.records
      //   this.partList.forEach(info => {
      //     // if(info.ACCEPT_AMOUNT == null || info.ACCEPT_AMOUNT == ''){
      //     //     // 审核的时间受理数量默认 = 0
      //     //     info.ACCEPT_AMOUNT = 0;
      //     // }
      //     // if(info.PJHSJE == null || info.PJHSJE == ''){
      //     //     // 审核的时间受理数量默认 = 0
      //     //     info.PJHSJE = 0;
      //     // }

      //   });
      // });

      getApproveRecord({ 'applyNum': this.applyNum }).then(response => {
        this.dataList1 = response.data.records
      }),
        this.approvalparams.applyNum = this.applyNum
      // this.approvalparams.xtsplx = 'tt_part_rtgoods'
      this.initForm.forEach(x => {
        if (x.fieldName === 'AUDIT_TIME') {
          x.initialValue = moment(data[x.fieldName]).format('YYYY-MM-DD HH:mm:ss');
        } else {
          x.initialValue = refundInfo.data[x.fieldName];
        }
      });
      getFileGroup({ "xtdjid": this.id, "xtfjlx": "tt_pt_claim_refund" }).then(response => {
        this.picFiles = response.data.records;
        this.picFiles.forEach(x => {
          x.xtwjmc = x.name;
          x.xtwjlj = x.url;
        });
      });
    },
    syncTableFun(val) {
      console.log(val, this.partList)
    },
    //取消操作
    closeDialog(type) {
      this.approveDialogFlag = false
      this.$emit('close', { visible: false, type: type });
    },
    initFormFun() {
      return [
        {
          type: 'INPUT',
          label: '服务商代码',
          fieldName: 'dealerCode',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
          // rules: [{
          //   required: true,
          //   message: '必填',
          //   trigger: 'blur'
          // }]
        },
        {
          type: 'INPUT',
          label: '服务商简称',
          fieldName: 'dealerName',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
          // rules: [{
          //   required: true,
          //   message: '必填',
          //   trigger: 'blur'
          // }]
        },
        {
          type: 'INPUT',
          label: '申请单号',
          fieldName: 'applyNum',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '理赔退货类型',
          fieldName: 'claimRefundType',
          placeholder: '请选择',
          initialValue: "",
          disabled: true,
          itemList: this.createDictList('3057'),
        },
        {
          type: 'SELECT',
          label: '申请原因',
          fieldName: 'applyCause',
          placeholder: '请选择',
          initialValue: "",
          disabled: true,
          itemList: this.createDictList('3058'),
        },
        {
          type: 'INPUT',
          label: '提报时间',
          fieldName: 'applyTime',
          placeholder: '请输入',
          initialValue: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'INPUT',
          label: '申请人',
          fieldName: 'applyByName',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '申请人电话',
          fieldName: 'applyPhone',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '交货单号',
          fieldName: 'bsysdh',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '交货单来源',
          fieldName: 'zjhdly',
          placeholder: '请选择',
          initialValue: "",
          disabled: true,
          // hidden: this.jhdInfodisabled,
          itemList: this.createDictList('3056'),
        },
        {
          type: 'INPUT',
          label: '发运时间',
          fieldName: 'bsfyrq',
          placeholder: '请输入',
          initialValue: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'INPUT',
          label: '签收时间',
          fieldName: 'bsqcrq',
          placeholder: '请输入',
          initialValue: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'INPUT',
          label: '承运单号',
          fieldName: 'coNo',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '物流单号',
          fieldName: 'traceNo',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '物流公司',
          fieldName: 'wsName',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '物流联系人',
          fieldName: 'wsPerson',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '物流联系电话',
          fieldName: 'wsPhone',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'TEXT_AREA',
          label: '申请说明',
          initialValue: '',
          selfCols: 3,
          maxlength: 150,
          fieldName: 'applyRemark',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'TEXT_AREA',
          label: '审核意见',
          initialValue: '',
          selfCols: 3,
          maxlength: 200,
          fieldName: 'auditRemark',
          placeholder: '请输入...',
          disabled: true
        }

        // {
        //   selfCols: 3,
        //   type: 'UPLOAD_FILE',
        //   label: '上传文件',
        //   fieldName: 'uploadFile',
        //   placeholder: '上传文件...',
        //   initialValue: '',
        //   disabled: true,
        //   upload: {
        //     actionUrl: `${config.uploadUrl}/api/file/oss/upload`,
        //     limit: 1,
        //     tipText: '（支持：pdf、rar、jpg、png格式）',
        //     fileTypes: ['pdf', 'rar', 'jpg', 'png'],
        //     data: {bucketType: 'public'}
        //   }
        // }
      ]
    },

    initFormFun2() {
      return [
        {
          type: 'TEXT_AREA',
          label: '审核意见',
          fieldName: 'xtspnr',
          placeholder: '请输入',
          initialValue: '',
          selfCols: 3
        }
      ]
    },
    changeHandle(val) {
      this.saveData = val
    },
    changeHandle2(val) {
      this.saveData2 = val
    },
    creatHeaderPartColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        { title: '备件代码', dataIndex: 'BJXMBH', sorter: true },
        // { title: '备件名称', dataIndex: 'BJZWMC', sorter: true,summationDataIndex: 'total', summation: true,summationUnit: '(申请品种合计)'},
        {
          title: '备件名称',
          dataIndex: 'BJZWMC',
          width: 220,
          summationDataIndex: 'total',
          summation: true,
          summationUnit: '(申请品种合计)',
          sorter: true
        },
        { title: '物料组', dataIndex: 'MATERIAL', dictItems: this.createDictList('3054'), sorter: true },
        { title: '服务商进价', dataIndex: 'XTJGJG', sorter: true, precision: 2, numberFormat: true },
        {
          title: '申请数量', dataIndex: 'APPLY_AMOUNT', sorter: true, summation: true, defaultEditable: true, defaultEditable: true,
          summation: true, summationUnit: '(申请数量合计)',
        },
        // { title: '申请单价', dataIndex: 'APPLY_MONEY', sorter: true,precision: 2,numberFormat: true },
        {
          title: '申请金额', dataIndex: 'APPLY_SUMAMOUNT', sorter: true, summation: true, precision: 2, summation: true, summationUnit: '(申请金额合计)', render: props => {
            props.row.APPLY_SUMAMOUNT = this.numberFormat(props.row.APPLY_AMOUNT * props.row.XTJGJG);
            return <span>{props.row.APPLY_SUMAMOUNT}</span>;
          }
        },
        {
          title: '受理单价', dataIndex: 'ACCEPT_MONEY', sorter: true, summation: false, defaultEditable: true, precision: 2
        },
        {
          title: '受理数量', dataIndex: 'ACCEPT_AMOUNT', sorter: true, summation: true, defaultEditable: true, summation: true, summationUnit: '(受理数量合计)',
        },
        // 受理金额 = 受理单价 * 受理数量
        {
          title: '受理金额', max:9999999999,dataIndex: 'ACCEPT_MONEY_SUM', sorter: true, summation: true, precision: 2, summation: true, summationUnit: '(受理金额合计)'
        },
        {
          title: '未受理数量', dataIndex: 'REJECT_AMOUNT', sorter: true, summation: true, summation: true, summationUnit: '(不受理数量合计)',
        },
        {
                title: '过账数量',
                // align:"center",
                dataIndex: 'bsfysl',
                sorter: true,
                hidden:false,
                summation: true,
                width: 150,
                summationUnit:"(过账数量合计)",
                numberFormat: true
            },
            {
                title: '过账金额',
                // align:"center",
                dataIndex: 'bsfyje',
                hidden:false,
                sorter: true,
                precision: 2,
                summation: true,
                summationUnit:"(过账金额合计)",
                width: 150,
                numberFormat: true
            },
            {
                title: '退库数量',
                // align:"center",
                dataIndex: 'returnedQuantity',
                sorter: false,
                summation: true,
                width: 150,
                summationUnit:"(退库数量合计)",
                hidden:false,
                numberFormat: true
            },
            {
                title: '开票金额',
                // align:"center",
                dataIndex: 'pjhsje',
                width: 150,
                sorter: true,
                precision: 2,
                hidden:false,
                summation: true,
                summationUnit:"(开票金额合计)",
                numberFormat: true
            },
      ];
    },
    creatHeaderApproveColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        { title: '审核人', dataIndex: 'AUDIT_BYNAME', sorter: true },
        { title: '审核状态', dataIndex: 'AUDIT_STATUS', dictItems: this.createDictList('3059'), sorter: true },
        { title: '审核日期', dataIndex: 'AUDIT_TIME', sorter: true, dateFormat: 'yyyy-MM-dd HH:mm:ss', },
        { title: '审核意见', dataIndex: 'AUDIT_REMARK', sorter: true }
      ];
    },


    closeRefuseDialog() {
      this.approveDialogFlag = false
    },

    syncPjFun(details) {
      console.log('details', details)
      this.formData.details = details
    },
    numberFormat(input) {
      if (!isNaN(Number(input))) {
        input = Number(input).toFixed(2);
      }
      input = this.formatNumber(input);
      return input
    },
    // 数字格式化
    formatNumber(value) {
      value += '';
      if (value.slice(-1) === '.') return value;
      value = value.replace(/,\s+/g, '');
      const list = value.split('.');
      const prefix = list[0].charAt(0) === '-' ? '-' : '';
      let num = prefix ? list[0].slice(1) : list[0];
      let result = '';
      while (num.length > 3) {
        result = `, ${num.slice(-3)}${result}`;
        num = num.slice(0, num.length - 3);
      }
      if (num) {
        result = num + result;
      }
      return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
    },

    createPicTable() {
      return [
        {
          title: '序号', dataIndex: 'index', width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作', dataIndex: 'column-action', width: 150, align: 'center',
          hidden: true,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deletePic(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '图片（支持格式：jpg, jpeg, png;）', dataIndex: 'name', align: 'center',
          render: p => {
            let fileType = this.getFileType(p.row.url);
            return fileType == 'pdf' ? (
              <a href={p.row.url} target="_blank">{p.row.name}</a>
            ) :
              (
                <div class="imgfile">
                  <img src={p.row.url} onClick={() => { this.imagesViewShow = true; this.picList = [p.row.url] }} alt="" />
                  <a href={p.row.url} target="_blank">{p.row.name}</a>
                </div>
              );
          }
        }
      ]
    },
    async deletePic(val) {
      this.$confirm('确定删除此文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let picIndex = 0;
        if (val.id != null && val.id > 0) {
          const res = await deletePartFileById(val.id, "part_rtgoods");
          if (res.resultCode === 200) {
            this.$refs.picTable.$refs.pageTable.EXECUTE_DELETE([val]);
            this.picFiles.forEach(x => {
              this.$set(x, 'index', picIndex++);
            });
            this.$notify.success({ title: '提示信息', message: '删除成功!' });
          }
        } else {
          this.$refs.picTable.$refs.pageTable.EXECUTE_DELETE([val]);
          this.picFiles.forEach(x => {
            this.$set(x, 'index', picIndex++);
          });
          this.$notify.success({ title: '提示信息', message: '删除成功!' });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    selectChange(val) {
      console.log('val', val);
    },
    // 上传成功回调
    successHandler(val) {
      if (val == 1) {
        this.picLoading = true;
      } else {
        this.picLoading = false;
        let data = { index: '', name: '', url: '', xtwjmc: '', xtwjlj: '' };
        let json = JSON.parse(JSON.stringify(val));
        this.$set(data, 'index', this.picFiles.length);
        this.$set(data, 'name', json[json.length - 1].name);
        this.$set(data, 'xtwjmc', json[json.length - 1].name);
        let furl = json[json.length - 1].url;
        this.$set(data, 'xtwjlj', furl);
        this.$set(data, 'url', furl);
        this.picFiles.push(data);
      }
    },
    async getPicUrl(url) {
      let actionUrl = this.uploadPrefix + '/api/file/download/url?fileUrl=' + url;
      let res = await axios.post(actionUrl);
      return res.data;
    },
    getFileType(fileName) {
      let fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length);
      return fileType.toLowerCase().split("?")[0];
    },
    closeImagesViewer() {
      this.imagesViewShow = false;
    },
  }
};
</script>
<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}

.el-table__body-wrapper {
  overflow-x: auto;
  position: static;
}

.el-image {
  float: left;
  margin-left: 130px;
}

.imgfile {
  height: 60px;
  line-height: 60px;
  overflow: hidden;
}

.imgfile a {
  float: left;
  margin-left: 20px;
}

.imgfile img {
  float: left;
  margin-left: 30%;
  width: 100px;
  height: 100%;
  object-fit: cover;
}

.pdfdiv {
  float: left;
  margin-left: 20%;
  width: 100px;
  height: 100%;
  object-fit: cover;
}
</style>
